<template>
  <div style="height: 80vh;">
    <el-dialog
      class="zdyplayDialog"
      ref="playSetting"
      top="38px"
      :before-close="closed"
      :close-on-click-modal="false"
      width="80%"
      :visible.sync="innerVisible"
      append-to-body>
      <span slot="title">
        <ul class="title_ul">
          <li>当前节目: <span style="color: #13CE66;">{{scopeRow.pgm_name}}</span></li>
          <li>节目属性: <span style="color: #13CE66;">{{scopeRow.pgm_attr === 2? '连续节目': '固定节目'}}</span></li>
          <li>长度： <time-picker style="display: inline;color: #13CE66;" format="HH:ii:ss" inputType="readonly" v-model="scopeRow.pgm_len"></time-picker></li>
          <li>{{scopeRow.first_flag=== 0 ? '重播': '首播'}}  <span style="color: #13CE66;">{{scopeRow.channel_name}}</span></li>
        </ul>
      </span>
      <el-card class="zdyplaySetCard" shadow="never" title="" style="padding: 0;">
        <div slot="header" class="clearfix">
          <span>播出周期安排</span>
<!--          <el-button style="float: right; padding: 6px 5px" type="text" @click="closed">取消</el-button>
          <el-button style="float: right; padding: 6px 5px" type="primary" @click="closed">保存</el-button> -->
          <el-button style="float: right;" type="primary" @click="createPlayDetail" :disabled="scopeRow.pgm_attr === 1" >生成明细</el-button>
        </div>
        <el-row :gutter="6">
          <el-col :span="3" v-for="item in weekConfig" :key="item.dayofweek">
            <div class="weekDay" @click="handleCurrWeekFun(item)">
              <p>{{ item.label }}</p>
              <template v-if="item.children">
                <div style="padding-left: 5px;">{{ item.children.play_num }} 集</div>
                <div><time-picker format="HH:ii:ss" style="display: inline-block;" inputType="readonly" v-model="item.children.s_time"></time-picker></div>
                <div v-if="scopeRow.pgm_attr === 2" style="padding-left: 5px;">两集间隔 <time-picker style="display: inline-block;" format="HH:ii:ss" inputType="readonly" v-model="item.children.time_space" /></div>
                <div v-else style="padding-left: 5px;">重播间隔 {{item.children.replay_space}}天</div>
              </template>
            </div>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="zdyplaySetCard" shadow="never" style="padding: 0 !important;">
<!--        <div slot="header" class="clearfix">
          <el-select v-model="year">
            <el-option v-for="item in yearArr" :key="item.value" :label="item.label"></el-option>
          </el-select>年
          <el-select v-model="month">
            <el-option v-for="item in monthArr" :key="item.value" :label="item.label"></el-option>
          </el-select>月
        </div> -->
        <play-calendar ref="calendar">
          <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
          <template
            slot="dateCell"
            slot-scope="{date, data}">
            <p :class="data.isSelected ? 'is-selected' : ''">
              {{ data.day.split('-').slice(1).join('-') }} <!-- {{ data.isSelected ? '✔️' : ''}} -->
            </p>
            <div v-if="playdateinfo[data.day] && scopeRow.pgm_attr === 2" class="playDetail">
              <p v-for="(item, index) in playdateinfo[data.day]"
                :class="{ 'active': clickindex === index + data.day }"
                @click="clickindex = index + data.day"
                :key="index"
                @dblclick="updatePlayDetail(item)">
                <span>
                  {{item.play_num}}集
                  <time-picker format="HH:ii:ss" inputType="readonly" v-model="item.play_time" style="display: inline;"></time-picker>
                </span>
                <span v-if="clickindex === index + data.day">
                  <el-popconfirm
                    @onConfirm="beforeMove(item, index)"
                    title="确认前移吗？">
                    <el-button slot="reference" type="text" title="左移" icon="el-icon-d-arrow-left" class="operatorMove" style="margin-right: 10px !important;"></el-button>
                  </el-popconfirm>

                  <el-popconfirm
                    @onConfirm="afterMove(item, index)"
                    title="确认后移吗？">
                    <el-button slot="reference" type="text" title="右移" icon="el-icon-d-arrow-right" class="operatorMove"></el-button>
                  </el-popconfirm>
                </span>
              </p>
            </div>

          </template>
        </play-calendar>
      </el-card>
      <el-dialog
        width="380px"
        title="节目周期安排"
        :visible.sync="childDialogVisible"
        :close-on-click-modal="false"
        center
        append-to-body>
        <el-form :model="playWeekForm" ref="playWeekFormRef" label-width="90px">
          <el-form-item label="">
            {{ weekConfig[playWeekForm.dayofweek - 1 || 0].label }}
          </el-form-item>
          <el-form-item label="集数">
            <el-input type="number" ref="playNum" @focus="$refs.playNum.select()" v-model="playWeekForm.play_num" class="elInputS"></el-input>
          </el-form-item>
          <el-form-item label="开始时间">
            <time-picker format="HH:ii:ss" v-model="playWeekForm.s_time" class="elInputS"/>
          </el-form-item>
          <el-form-item label="间隔时间">
            <time-picker format="HH:ii:ss" v-model="playWeekForm.time_space" class="elInputS"/>
          </el-form-item>
          <el-form-item label="重播间隔">
            <el-input type="number" ref="replaceSpace" @focus="$refs.replaceSpace.select()" v-model="playWeekForm.replay_space" class="elInputS"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="childDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPlaySet" v-on:keyup.13="submitPlaySet">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        width="480px"
        title="调整播放时间"
        :visible.sync="playUpdateVisible"
        :close-on-click-modal="false"
        center
        append-to-body>
        <el-form :model="playDetailForm" ref="playDetailFormRef" label-width="90px">
          <el-form-item label="">
            {{ playDetailForm.play_num }} 集
          </el-form-item>
          <el-form-item label="原时间">
            {{playDetailForm.play_date}} - <time-picker format="HH:ii:ss" inputType="readonly" v-model="playDetailForm.play_time" style="display: inline;"></time-picker>
          </el-form-item>
          <el-form-item label="新时间">
            <el-date-picker
              v-model="playDetailForm.new_play_date"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              class="elInputS">
            </el-date-picker>
            <time-picker format="HH:ii:ss" v-model="playDetailForm.new_play_time" class="elInputXS"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="playUpdateVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitputDetail">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import commonMethods from '@/utils/commonMethods.js'
import pgmPlayPlan from '@/api/pgmmanage/pgmplan.js'
const playform = { play_num: 0, replay_space: 0, s_time: 0, time_space: 0 }

export default {
  name: 'playsetting',
  mixins: [commonMethods],
  watch: {
    'playdateinfo'(newV) {
      console.log(newV, 'change')
    }
  },
  data() {
    return {
      // 星期配置
      weekConfig: [
        { dayofweek: 1, label: '星期一' },
        { dayofweek: 2, label: '星期二' },
        { dayofweek: 3, label: '星期三' },
        { dayofweek: 4, label: '星期四' },
        { dayofweek: 5, label: '星期五' },
        { dayofweek: 6, label: '星期六' },
        { dayofweek: 7, label: '星期日' }
      ],
      childDialogVisible: false,
      playUpdateVisible: false,
      playWeekForm: playform, // 播放安排表单
      playWeekFormRules: [],
      playDetailForm: {},
      playDetailFormRules: [],
      clickindex: undefined,
      playdateinfo: {}
    }
  },
  props: {
    mattype: {
      type: String,
      default: 'all'
    },
    innerVisible: {
      type: Boolean,
      default: false
    },
    scopeRow: {
      type: Object,
      default: null
    }
  },
  created() {
    for (const item of this.weekConfig) {
      item.pgm_id = this.scopeRow.pgm_id
      item.play_id = this.scopeRow.play_id
    }
    this.getpgmplayplan()
  },
  mounted() {
    console.log(this.scopeRow)
  },
  methods: {
    closed() {
      this.$emit('close')
    },
    updateWeekConfig(item) { // 更新星期配置
      const nowCurrObj = this.weekConfig[item.dayofweek - 1]
      nowCurrObj.children = item
      this.weekConfig.splice(item.dayofweek - 1, 1, nowCurrObj)
    },
    handleCurrWeekFun(item) { // 设置表单对象
      if (item.children) {
        this.playWeekForm = JSON.parse(JSON.stringify(item.children))
      } else {
        const newForm = {}
        newForm.pgm_id = item.pgm_id
        newForm.play_id = item.play_id
        newForm.dayofweek = item.dayofweek
        Object.assign(newForm, playform)
        this.playWeekForm = JSON.parse(JSON.stringify(newForm))
      }
      this.childDialogVisible = true
      this.$nextTick(() => {
        this.$refs.playNum.focus()
      })
    },
    submitPlaySet() {
      this.pgmplayplanAdd(this.playWeekForm)
      console.log(this.weekConfig)
    },
    handleClick(date, data) {
      console.log(date, data)
    },
    // 获取节目频道播出计划
    getpgmplayplan() {
      pgmPlayPlan.list({
        pgm_id: this.scopeRow.pgm_id,
        play_id: this.scopeRow.play_id
      }).then(res => {
        const playinfo = res.data.data || []
        playinfo.map(item => {
          this.updateWeekConfig(item) // 更新每周节目安排配置
        })

        this.getPlayDetail() // 获取播出日期安排明细
      })
    },
    // 获取播出安排明细
    getPlayDetail() {
      pgmPlayPlan.detailList({
        pgm_id: this.scopeRow.pgm_id,
        play_id: this.scopeRow.play_id
      }).then(res => {
        const newObj = this.computedMonthPlayInfo(res.data.data || [])
        Object.keys(newObj).map(item => {
          this.$set(this.playdateinfo, item, newObj[item])
        })

        this.$nextTick(() => {
          this.$refs.calendar.pickDay(this.scopeRow.s_play_date)
        })
      })
    },
    // 后台获取的节目明细数组，按日期整理归纳。
    computedMonthPlayInfo(lists) {
      const tmpObj = {}
      lists.map(item => {
        if (tmpObj[item.play_date] === undefined) {
          tmpObj[item.play_date] = [item]
        } else {
          tmpObj[item.play_date].push(item)
        }
      })
      return tmpObj
    },

    // 节目频道播出计划添加
    pgmplayplanAdd(form) {
      if (!form) return
      pgmPlayPlan.add(form).then(res => {
        this.childDialogVisible = false
        this.$nextTick(() => {
          this.updateWeekConfig(this.playWeekForm) // 更新每周节目安排配置
        })
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    },
    // 创建播出明细
    async createPlayDetail() {
      const playDate = this.weekConfig.filter(item => item.children === undefined)
      if (playDate.length > 0) {
        return this.$alert('请将每天的节目安排好后，再生成明细!', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }

      const confirmresult = await this.$alert(
        `您确信已经安排好了节目播放周期，现在要进行明细生成吗？
        如果播出安排作了个别调整，那么明细生成后要重新进行个别调整！`,
        '提示',
        {
          confirmButtonText: '确定',
          showCancelButton: true,
          cancelButtonText: '取消',
          customClass: 'zdyconfirm',
          closeOnClickModal: false,
          type: 'warning'
        }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return false
      }

      // this.playdateinfo['2021-04-10'].pop()
      // console.log(this.weekConfig)
      // console.log(this.scopeRow)

      this.playdateinfo = this.PlayDetail()
      this.submitPlayDetail() // 提交明细保存
      this.$nextTick(() => {
        this.$refs.calendar.pickDay(this.scopeRow.s_play_date)
      })
    },
    // 播出安排明细提交保存
    submitPlayDetail() {
      const newList = this.productSavelist(this.playdateinfo) // 遍历生成连续节目单数组
      pgmPlayPlan.addDetails({
        pgm_id: this.scopeRow.pgm_id,
        play_id: this.scopeRow.play_id,
        list: newList
      }).then(res => {
        this.getPlayDetail()
      })
    },
    // 生成连续节目数组方法
    productSavelist(obj) {
      let newList = []
      Object.keys(obj).map(item => {
        newList = newList.concat(obj[item])
      })
      return newList
    },
    PlayDetail() {
      if (this.scopeRow.sum_num < 1) {
        // 节目总集数小于1，退出
        return false
      }

      let date = this.scopeRow.s_play_date // 首播开始日期
      let sum = 0 // 当前已设置集数
      const playObj = {}

      while (sum < this.scopeRow.sum_num) {
        const tempD = new Date(date) // 起始日期
        const datekey = this.getweekKey(tempD) // 获取当天星期的key键
        const play_num = this.weekConfig[datekey].children.play_num // 当天设置电视剧集数

        if (play_num === 0) {
          // 当天集数为0 ,跳到下一天检查
          date = this.getNextDay(date)
          continue
        }

        const currdate = this.getCurrDate(tempD)
        playObj[currdate] = []
        for (let i = 0; i < play_num; i++) {
          /* todo 在此处生成节目明细对象 */
          const detail = this.createpgmInfo(this.scopeRow, tempD, sum + 1, i, datekey, playObj)
          playObj[currdate].push(detail)

          sum++
        }
        date = this.getNextDay(date)
      }
      return playObj
    },
    getweekKey(date) {
      return date.getDay() === 0 ? 6 : date.getDay() - 1
    },
    // 获取前一天，有效播放日
    getBeforeDay(dayStr) {
      var dd = new Date(dayStr)
      dd.setDate(dd.getDate() - 1)
      var y = dd.getFullYear()
      var m = dd.getMonth() + 1 // 获取当前月份的日期
      var d = dd.getDate()
      var day = y + '-' + String(m).padStart('2', '0') + '-' + String(d).padStart('2', '0')

      const datekey = this.getweekKey(new Date(day)) // 获取当天星期的key键
      const play_num = this.weekConfig[datekey].children.play_num // 当天设置电视剧集数

      if (play_num === 0) {
        // 当天集数为0 ,跳到下一天检查
        return this.getBeforeDay(day)
      } else {
        return day
      }
    },
    // 获取下一天，有效播放日
    getAfterDay(dayStr) {
      var dd = new Date(dayStr)
      dd.setDate(dd.getDate() + 1)
      var y = dd.getFullYear()
      var m = dd.getMonth() + 1 // 获取当前月份的日期
      var d = dd.getDate()
      var day = y + '-' + String(m).padStart('2', '0') + '-' + String(d).padStart('2', '0')

      const datekey = this.getweekKey(new Date(day)) // 获取当天星期的key键
      const play_num = this.weekConfig[datekey].children.play_num // 当天设置电视剧集数

      if (play_num === 0) {
        // 当天集数为0 ,跳到下一天检查
        return this.getAfterDay(day)
      } else {
        return day
      }
    },
    // 获取下一天
    getNextDay(dayStr) {
      var dd = new Date(dayStr)
      dd.setDate(dd.getDate() + 1)
      var y = dd.getFullYear()
      var m = dd.getMonth() + 1 // 获取当前月份的日期
      var d = dd.getDate()
      return y + '-' + String(m).padStart('2', '0') + '-' + String(d).padStart('2', '0')
    },
    // 获取当天日期
    getCurrDate(dayStr) {
      var dd = new Date(dayStr)
      var y = dd.getFullYear()
      var m = dd.getMonth() + 1 // 获取当前月份的日期
      var d = dd.getDate()
      return y + '-' + String(m).padStart('2', '0') + '-' + String(d).padStart('2', '0')
    },
    // 生成连续剧节目明细
    createpgmInfo(scopeRow, day, play_num, index, datekey, playObj) {
      const currdate = this.getCurrDate(day)
      let play_time
      if (index === 0) {
        play_time = this.weekConfig[datekey].children.s_time
      } else {
        play_time = playObj[currdate][index - 1].play_time + scopeRow.pgm_len + this.weekConfig[datekey].children.time_space
      }
      return {
        pgm_id: scopeRow.pgm_id,
        play_id: scopeRow.play_id,
        play_num,
        pgm_name: scopeRow.pgm_name + `第${play_num}集${scopeRow.first_flag === 0 ? '(重)' : ''}`,
        pgm_type: scopeRow.pgm_type,
        pgm_len: scopeRow.pgm_len,
        play_date: this.getCurrDate(day),
        play_time,
        mat_id: '',
        tape_code: '',
        tc_type: '',
        markin: 0,
        markout: 0,
        pgm_attr: scopeRow.pgm_attr
      }
    },
    updatePlayDetail(info) {
      this.playUpdateVisible = true
      this.playDetailForm = info
      this.$set(this.playDetailForm, 'new_play_date', info.play_date)
      this.$set(this.playDetailForm, 'new_play_time', info.play_time)
    },
    async submitputDetail() {
      this.playUpdateVisible = false
      const confirmresult = await this.$alert(
        '您需要修改后面所有节目的开始时间吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'zdyconfirm',
          closeOnClickModal: false,
          showCancelButton: true,
          type: 'warning'
        }).catch(err => err)
      let putplayForm = []
      const rows = JSON.parse(JSON.stringify(this.playDetailForm)) // 当选设置明细行
      const playdateinfo = JSON.parse(JSON.stringify(this.playdateinfo)) // 日历安排明细
      if (confirmresult !== 'confirm') { // 取消
        rows.play_time = rows.new_play_time
        rows.play_date = rows.new_play_date
        putplayForm.push(rows)
      } else { // 确定
        putplayForm = this.moreUpdateDetail(rows, playdateinfo)
      }
      // 更新明细
      pgmPlayPlan.putDetails({
        list: putplayForm
      }).then(res => {
        if (res.data.meta.status === 200) {
          this.getPlayDetail()
        }
      })
    },
    // 获取批量更新的明细数组
    moreUpdateDetail(row, obj) {
      const newUpArr = []
      const daysArr = obj[row.play_date] // 得到当日播放信息数组
      let curindex // 记录当日修改的播放安排序号下标
      daysArr.map((item, index) => {
        if (item.seq === row.seq) {
          curindex = index
        }
      })

      const nowIndex = Object.keys(obj).indexOf(row.play_date) // 得到当日对应键下标
      const nextArr = Object.keys(obj).slice(nowIndex)
      nextArr.map(item => {
        if (obj[item][curindex] !== undefined) {
          obj[item][curindex].play_time = row.new_play_time // 将后面对应下标的播出时间统一修改
          newUpArr.push(obj[item][curindex])
        }
      })
      return newUpArr
    },
    // 前移
    beforeMove(row, index) {
      if (index > 0) {
        return this.$alert('只有当天的第一条节目可以前移！', '', {
          confirmButtonText: '确定',
          type: 'error',
          callback: function() {
            console.log('close1')
          }
        })
      }
      const CurrDay = row.play_date // 当前节目排版日期
      const nowRow = this.playdateinfo[CurrDay].shift() //  将当前剧集移除当天播放安排
      const beforeDay = this.getBeforeDay(CurrDay)
      if (this.playdateinfo[beforeDay] === undefined) {
        nowRow.play_date = beforeDay
        this.playdateinfo[beforeDay] = [nowRow]
      } else {
        nowRow.play_date = beforeDay
        this.playdateinfo[beforeDay].push(nowRow)
      }

      const dateArr = Object.keys(this.playdateinfo).sort((a, b) => Date.parse(a) - Date.parse(b))
      const curindex = dateArr.indexOf(CurrDay) // 获取当前操作天的下标
      const nextArr = dateArr.slice(curindex)

      nextArr.map((item, index) => {
        if (nextArr[index + 1] !== undefined) {
          const nextpgm = this.playdateinfo[nextArr[index + 1]].shift()
          if (nextpgm !== undefined) {
            nextpgm.play_date = item
            this.playdateinfo[item].push(nextpgm)
          }
        }
      })
      this.submitPlayDetail() // 提交保存
    },
    // 后移
    afterMove(row, index) {
      const CurrDay = row.play_date // 当前节目排版日期
      const dateArr = Object.keys(this.playdateinfo).sort((a, b) => Date.parse(a) - Date.parse(b))
      const curindex = dateArr.indexOf(CurrDay) // 获取当前操作天的下标
      const nextArr = dateArr.slice(curindex)

      // 逆向顺序将节目后移
      nextArr.reverse().map((item, index) => {
        if (index === 0) { // 根据最后一天的节目是否排满，选择是否向后天安排
          const nums = this.playdateinfo[item].length
          const datekey = this.getweekKey(new Date(item)) // 获取当天星期的key键
          const play_num = this.weekConfig[datekey].children.play_num // 当天设置电视剧集数
          if (nums < play_num) { // 最后一天节目未排满,跳出循环
            return false
          }
        }

        // 后移节目， 讲当前日期最后一条节目移除，插入到后一天（有效安排日期）的第一条中去
        const nowRow = this.playdateinfo[item].pop()
        const afterDay = this.getAfterDay(item)
        if (nowRow !== undefined) {
          if (this.playdateinfo[afterDay] === undefined) {
            nowRow.play_date = afterDay
            this.playdateinfo[afterDay] = [nowRow]
          } else {
            nowRow.play_date = afterDay
            this.playdateinfo[afterDay].unshift(nowRow)
          }
        }
      })
      this.submitPlayDetail() // 提交保存
    },
    cancelSure() {
      console.log('取消')
    }
  }
}
</script>

<style lang="less">
.title_ul {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
  margin-bottom: 12px;
}
.title_ul li {
  margin-right: 30px;
  font-size: 15px;
  font-weight: bold;
  color: #f2f2f2;
}

.weekDay {
  width: 100%;
  height: 110px;
  margin: 2px;
  background-color: skyblue;
  border: 1px solid #1E1E1E;
  cursor: pointer;
}
.weekDay p {
  padding: 0 5px;
  margin: 4px 0;
  color: #795DA3;
}

.weekDay span {
  padding: 2px 5px;
}

.el-calendar-day {
  overflow-y: auto;
  height: 100px !important;
}
.el-calendar-day > p {
  margin: 0;
}
.playDetail p{
  margin: 2px 0;
  padding: 1px 3px;
  color: #1989FA;
}
.playDetail p.active {
  background-color: #42b983;
  color: #2e4e7d;
  display: flex;
  justify-content: space-between;
}
.operatorMove {
  margin: 0 !important;
  padding: 0 !important;
  color: #fff !important;
}
.zdyconfirm {
  z-index: 9999 !important;
}
.zdyplayDialog .el-dialog__body {
  padding-top: 0px !important;
}
.zdyplaySetCard .el-card__body {
  padding: 0 !important;
}

</style>
